package be.shoktan.tutorial.chapterThree;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;

import com.opensymphony.xwork2.ModelDriven;

import be.shoktan.tutorial.BaseAction;
import be.shoktan.tutorial.model.User;
import be.shoktan.tutorial.services.PortfolioService;

public class Register extends BaseAction implements ModelDriven<User>{
	private static final long serialVersionUID = 5524654183080848167L;
	private static final Logger LOG = Logger.getLogger(Register.class);
	
	private User user = new User();
	
	public User getModel(){
		return user;
	}
	
	private String parrain;
	
	


	public String getParrain() {
		return parrain;
	}


	public void setParrain(String parrain) {
		if(LOG.isTraceEnabled())LOG.trace("setParrain("+parrain+")");
		this.parrain = parrain;
	}


	public String execute(){
		if(LOG.isTraceEnabled())LOG.trace("executing");
		PortfolioService ps = getPortfolioService();
		ps.createAccount(user);
		return SUCCESS;
	}
	
	
	public void validate(){
		if(LOG.isTraceEnabled())LOG.trace("validating");
		PortfolioService ps = getPortfolioService();
		
		if(StringUtils.length(user.getPassword()) == 0){
			addFieldError("password", "Password is required.");
		}
		if(StringUtils.length(user.getUsername()) == 0){
			addFieldError("username", "Username is required.");
		}
		if(StringUtils.length(user.getPortfolioName()) == 0){
			addFieldError("portfolioName", "Portfolio name is required.");
		}
		if(ps.userExists(user.getUsername())){
			addFieldError("username", "This user already exists");
		}
	}
	
	public PortfolioService getPortfolioService(){
		return PortfolioService.getInstance();
	}

}
